package com.xuchen.zhenyang.entity.base;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xuchen.zhenyang.base.BaseQuery;

import java.util.Date;

public class MyEntityWrapper<T> extends EntityWrapper<T> {

    private T myEntity;
    private BaseQuery baseQuery;

    public MyEntityWrapper() {
    }

    public MyEntityWrapper(BaseQuery baseQuery, T myEntity) {
        this.myEntity = myEntity;
        if (baseQuery == null) {
            baseQuery = new BaseQuery();
        }
        this.baseQuery = baseQuery;
        baseQuery.startPage();
        this.orderBy(baseQuery.getPageField(), "asc".equals(baseQuery.getPageOrder()));
    }

    public MyEntityWrapper<T> like(String column) {
        Object columnValue = ReflectUtil.getFieldValue(myEntity, StrUtil.toCamelCase(column));
        if (columnValue != null) {
            super.like(column, String.valueOf(columnValue));
        }
        return this;
    }

    public MyEntityWrapper<T> eq(String column) {
        Object columnValue = ReflectUtil.getFieldValue(myEntity, StrUtil.toCamelCase(column));
        if (columnValue != null) {
            super.eq(column, columnValue);
        }
        return this;
    }

    public MyEntityWrapper<T> ge(String column, Object columnValue) {
        if (columnValue == null){
            return this;
        }
        if (columnValue instanceof String){
            if (StrUtil.isNotBlank((String) columnValue)) {
                super.ge(column, columnValue);
            }
        }else {
            super.ge(column, columnValue);

        }
        return this;
    }

    public MyEntityWrapper<T> le(String column, Object columnValue) {
        if (columnValue == null){
            return this;
        }
        if (columnValue instanceof String){
            if (StrUtil.isNotBlank((String) columnValue)) {
                super.le(column, columnValue);
            }
        }else {
            super.le(column, columnValue);
        }
        return this;
    }

    public MyEntityWrapper<T> timeBetween(String column) {
        Date beginDate = baseQuery.getBeginDate();
        Date endDate = baseQuery.getEndDate();
        if (beginDate != null && endDate != null) {
            if (beginDate.before(endDate)) {
                super.between(column, beginDate, endDate);
            }
        } else if (beginDate != null) {
            super.gt(column, beginDate);
        } else if (baseQuery.getEndDate() != null) {
            super.lt(column, endDate);
        }
        return this;
    }
}
